package com.ajview.core.manage;

import com.ajview.common.utils.ThreadUtils;
import com.ajview.common.utils.spring.SpringUtils;

import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * PROJECT_NAME: ajview-smile
 *
 * @DESCRIPTION: 异步任务管理器
 * @DATE 2022-12-28 上午 01:10
 * @Author zhangjunjie
 */
public class AsyncManager {

    /**
     * 操作延迟10毫秒
     */
    private static final int OPERATE_DELAY_TIME = 10;
    private static AsyncManager instance = new AsyncManager();
    /**
     * 异步操作任务调度线程池
     */
    private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService");

    /**
     * 单例模式
     */
    private AsyncManager() {
    }

    public static AsyncManager getInstance() {
        return instance;
    }


    /**
     * 执行任务
     *
     * @param task 任务
     */
    public void execute(TimerTask task) {
        executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    /**
     * 停止任务线程池
     */
    public void shutdown() {
        ThreadUtils.shutdownAndAwaitTermination(executor);
    }

}
